package com.toweave.starter.fragments;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.DialogFragment;

import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.toweave.starter.R;
import com.toweave.starter.utils.DisplayUtil;

public class AsBottomSheetDialogFragment extends BottomSheetDialogFragment {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // 在onCreate()中设置样式
    setStyle(DialogFragment.STYLE_NORMAL, R.style.AsBottomSheetDialog);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_as_bottom_sheet_dialog, container, false);
    return view;
  }

  @Override
  public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // 此时view已经被添加到它的父视图，可以安全地获取parent
    View bottomSheet = (View) view.getParent();
    Context ctx = requireContext();
    bottomSheet.setBackground(ContextCompat.getDrawable(requireContext(), R.drawable.bottom_sheet_dialog_background));
    // Set the padding to account for the rounded corners if needed
    int paddingDp = 8; // for example, the padding in dp
    int paddingPx = DisplayUtil.dpToPx(ctx, paddingDp);
    bottomSheet.setPadding(paddingPx, paddingPx, paddingPx, paddingPx);
  }

  @Override
  public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null) {
      View bottomSheet = dialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
      if (bottomSheet != null) {
        BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        // 设置peekHeight为屏幕高度的 400
        bottomSheetBehavior.setPeekHeight(400);
        // 设置状态为展开状态
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
      }

      // 设置对话框高度为屏幕高度的90%
      Window window = dialog.getWindow();
      if (window != null) {
        window.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams params = window.getAttributes();
        params.height = (int) (getResources().getDisplayMetrics().heightPixels * 0.9);
        window.setAttributes(params);
      }
    }
  }
}